package com.example.firebase.test;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.messaging.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class FireBaseUtil {

    static Logger logger = LoggerFactory.getLogger(FireBaseUtil.class);

    // 存放多个实例的Map
    private static Map<String, FirebaseApp> firebaseAppMap = new ConcurrentHashMap<>();
    // 获取AndroidConfig.Builder对象
    private static com.google.firebase.messaging.AndroidConfig.Builder androidConfigBuilder = AndroidConfig.builder();
    // 获取AndroidNotification.Builder对象
    private static AndroidNotification.Builder androidNotifiBuilder = AndroidNotification.builder();
    // 获取应用名
    private static String appName = "com.zh.abc";

    /**
     * 判断SDK是否初始化
     *
     * @param appName
     * @return
     */
    public static boolean isInit(String appName) {
        return firebaseAppMap.get(appName) != null;
    }

    /**
     * 初始化SDK
     *
     * @param jsonPath JSON路径
     * @param dataUrl  firebase数据库
     * @param appName  APP名字
     * @throws IOException
     */
    public static void initSDK(String jsonPath, String dataUrl, String appName) throws IOException {
        FileInputStream serviceAccount = new FileInputStream(jsonPath);
        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredentials(GoogleCredentials.fromStream(serviceAccount)).setDatabaseUrl(dataUrl).build();
        // 初始化firebaseApp
        FirebaseApp firebaseApp = FirebaseApp.initializeApp(options);
        logger.info("firebaseApp:  "+ firebaseApp.toString());
        // 存放
        firebaseAppMap.put(appName, firebaseApp);
    }

    /**
     * 单设备推送
     *
     * @param appName 应用的名字
     * @param token   注册token
     * @param title   推送题目
     * @param bady    推送内容
     * @return
     * @throws IOException
     * @throws FirebaseMessagingException
     */
    public static String pushSingle(String appName, String token, String title, String body)
            throws IOException, FirebaseMessagingException {
        String messageId = null;
        // 获取实例
        FirebaseApp firebaseApp = firebaseAppMap.get(appName);
        // 实例为空的情况
        if (firebaseApp == null) {
            return messageId;
        }
        // 构建消息内容
        Message message = Message.builder().setNotification(new Notification(title, body)).setToken(token).build();
        // 发送后，返回messageID
        messageId = FirebaseMessaging.getInstance(firebaseApp).send(message);
        System.out.println("单个设备推送成功 : " + messageId);
        return messageId;
    }

    /**
     * 给设备订阅主题
     *
     * @param appName 应用的名字
     * @param Tokens  设备的token,最大1000个
     * @param topic   要添加的主题
     * @return
     * @throws FirebaseMessagingException
     * @throws IOException
     */
    public static TopicManagementResponse registrationTopic(String appName, List<String> tokens, String topic)
            throws FirebaseMessagingException, IOException {
        TopicManagementResponse response = null;
        // 获取实例
        FirebaseApp firebaseApp = firebaseAppMap.get(appName);
        // 实例不存在的情况
        if (firebaseApp == null) {
            return response;
        }
        // 订阅，返回主题管理结果对象
        response = FirebaseMessaging.getInstance(firebaseApp).subscribeToTopic(tokens, topic);
//	        response.get
        System.out.println(response.getErrors().size());
        ;

        System.out.println("添加设备主题，成功：" + response.getSuccessCount() + ",失败：" + response.getFailureCount());
        return response;
    }

    /**
     * 取消设备的订阅主题
     *
     * @param appName 应用的名字
     * @param tokens  设备的token,最大1000个
     * @param topic   取消的主题
     * @return
     * @throws FirebaseMessagingException
     * @throws IOException
     */
    public static void cancelTopic(String appName, List<String> tokens, String topic)
            throws FirebaseMessagingException, IOException {
        // 获取实例
        FirebaseApp firebaseApp = firebaseAppMap.get(appName);
        // 实例不存在的情况
        if (firebaseApp == null) {
            return;
        }
        // 取消订阅，返回主题管理结果对象。
        TopicManagementResponse response = FirebaseMessaging.getInstance(firebaseApp).unsubscribeFromTopic(tokens,
                topic);
        System.out.println("取消设备主题，成功：" + response.getSuccessCount() + ",失败：" + response.getFailureCount());
    }

    /**
     * 按主题推送
     *
     * @param appName 应用的名字
     * @param topic   主题的名字
     * @param title   消息题目
     * @param body    消息体
     * @return
     * @throws FirebaseMessagingException
     * @throws IOException
     */
    public static String sendTopicMes(String appName, String topic, String title, String body)
            throws FirebaseMessagingException, IOException {
        String messageID = null;
        // 获取实例
        FirebaseApp firebaseApp = firebaseAppMap.get(appName);
        // 实例不存在的情况
        if (firebaseApp == null) {
            return messageID;
        }
        // 构建消息
        Message message = Message.builder().setNotification(new Notification(title, body)).setTopic(topic).build();
        // 发送后，返回messageID
        messageID = FirebaseMessaging.getInstance(firebaseApp).send(message);
        System.out.println("主题推送成功: " + messageID);
        return messageID;
    }

    /**
     * 单条Android设备推送消息(和pushSingle方法几乎没有区别)
     *
     * @param appName 应用的名字
     * @param token   注册token
     * @param title   推送题目
     * @param bady    推送内容
     * @throws FirebaseMessagingException
     */
    public static void pushSingleToAndroid(String appName, String token, String title, String body)
            throws FirebaseMessagingException {
        // 获取实例
        FirebaseApp firebaseApp = firebaseAppMap.get(appName);
        // 实例为空的情况
        if (firebaseApp == null) {
            return;
        }
        androidConfigBuilder.setRestrictedPackageName("io.telecomm.telecomm");
        androidNotifiBuilder.setColor("#55BEB7");// 设置消息通知颜色
        androidNotifiBuilder.setIcon("https://www.shiku.co/images/favicon.png");// 设置消息图标
        androidNotifiBuilder.setTitle(title);// 设置消息标题
        androidNotifiBuilder.setBody(body);// 设置消息内容
        AndroidNotification androidNotification = androidNotifiBuilder.build();
        androidConfigBuilder.setNotification(androidNotification);
        AndroidConfig androidConfig = androidConfigBuilder.build();
        // 构建消息
        Message message = Message.builder().setToken(token).setAndroidConfig(androidConfig).build();
        // 发送后，返回messageID
        String response = FirebaseMessaging.getInstance(firebaseApp).send(message);
        System.out.println("单个安卓设备推送成功 : " + response);
    }

    /**
     * Android按主题推送(和sendTopicMes方法几乎没有区别)
     *
     * @param appName 应用的名字
     * @param topic   主题的名字
     * @param title   消息题目
     * @param body    消息体
     * @return
     * @throws FirebaseMessagingException
     * @throws IOException
     */
    public static void sendTopicMesToAndroid(String appName, String topic, String title, String body)
            throws FirebaseMessagingException, IOException {
        // 获取实例
        FirebaseApp firebaseApp = firebaseAppMap.get(appName);
        // 实例为空的情况
        if (firebaseApp == null) {
            return;
        }
        androidNotifiBuilder.setColor("#55BEB7");// 设置消息通知颜色
        androidNotifiBuilder.setIcon("https://www.shiku.co/images/favicon.png");// 设置消息图标
        androidNotifiBuilder.setTitle(title);// 设置消息标题
        androidNotifiBuilder.setBody(body);// 设置消息内容
        AndroidNotification androidNotification = androidNotifiBuilder.build();
        androidConfigBuilder.setNotification(androidNotification);
        AndroidConfig androidConfig = androidConfigBuilder.build();
        // 构建消息
        Message message = Message.builder().setTopic(topic).setAndroidConfig(androidConfig).build();
        String response = FirebaseMessaging.getInstance(firebaseApp).send(message);
        System.out.println("安卓主题推送成功: " + response);
    }

    public static String getAppName() throws IOException {
        if (StringUtils.isEmpty(appName)) {
           /* String firebaseServiceAccount = ConfigUtil.getProperty("firebase.serviceAccount");
            logger.error("firebaseServiceAccount:   "+ firebaseServiceAccount);
            String jsonPath = FireBaseUtil.class.getResource(firebaseServiceAccount).getPath();
            String jsonFile = FileUtils.readFileToString(new File(jsonPath));
            logger.error("jsonPath:   "+ jsonPath);
            logger.error("jsonFile:   "+ jsonFile);
            JSONObject adminsdkJson = JSONObject.parseObject(jsonFile);
            appName = adminsdkJson.getString("project_id");*/
        }
        return appName;
    }

    //初始化
    public static void init() throws IOException {
        System.setProperty("proxyHost", "127.0.0.1");
        System.setProperty("proxyPort", "50731");//1080
        String appName = getAppName();
        if (!StringUtils.isEmpty(appName)) {
            if (!isInit(appName)) {
                //google那边一个json串的文件,终端自己申请给你
                //String firebaseServiceAccount = ConfigUtil.getProperty("firebase.serviceAccount");
                // firebase.databaseUrl=https://xmediatv-197503.firebaseio.com 配置文件
                String jsonPath = "C:/Users/ls/Downloads/hancock-6ed71-firebase-adminsdk-oa2o5-cb29e6d5ec.json";/*FireBaseUtil.class.getResource(firebaseServiceAccount).getPath();*/
                String dataUrl = "";/*ConfigUtil.getProperty("firebase.databaseUrl");*/

                // 初始化FirebaseApp
                initSDK(jsonPath, dataUrl, appName);
            }
        }
    }

    /**
     * 注册主题
     *
     * @param token
     * @param topic
     * @return
     */
    public static boolean registTopic(String token, String topic) {
        boolean isRegist = false;
        try {
            init();
            List<String> tokens = new ArrayList<>(1);
            TopicManagementResponse response = registrationTopic(appName, tokens, topic);
            if (response.getSuccessCount() > 0) {
                isRegist = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isRegist;
    }

    /**
     * 批量注册主题
     *
     * @param tokens
     * @param topic  ATV
     * @return
     */
    public static TopicManagementResponse registListTopic(List<String> tokens, String topic) {
        TopicManagementResponse response = null;
        try {
            init();
            response = registrationTopic(appName, tokens, topic);
            if (response.getSuccessCount() > 0) {
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 发送单信息
     *
     * @param topic
     * @param title
     * @param body
     * @return
     */
    public static boolean sendSingleMessage(String token, String title, String body) {
        boolean status = false;
        try {
            init();
            String messsageId = pushSingle(appName, token, title, body);
            if (!StringUtils.isEmpty(messsageId)) {
                status = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return status;
    }

    /**
     * 发送主题信息
     *
     * @param topic
     * @param title
     * @param body
     * @return
     */
    public static boolean sendTopicMessage(String topic, String title, String body) {
        boolean status = false;
        try {
            init();
            String messsageId = sendTopicMes(appName, topic, title, body);
            if (!StringUtils.isEmpty(messsageId)) {
                status = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return status;
    }

    /**
     * 发送主题消息
     *
     * @param message
     * @return
     */
    public static String sendTopicMessage(Message message) {
        String sendResp = null;
        if (null == message) {
            return sendResp;
        }
        try {
            init();
            // 获取实例
            FirebaseApp firebaseApp = firebaseAppMap.get(appName);
            // 实例不存在的情况
            if (firebaseApp == null) {
                return sendResp;
            }
            // 发送后，返回
            sendResp = FirebaseMessaging.getInstance(firebaseApp).send(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sendResp;
    }

}